package com.hong.servicehosp.aspect;

import com.hong.commonutil.exception.YyghException;
import com.hong.commonutil.result.ResultCodeEnum;
import com.hong.model.vo.order.OrderMqVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class HospitalAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @Around("execution(public * com.hong.servicehosp.recevier.HospitalReceiver.receiver(..))")
    public Object Lock(ProceedingJoinPoint pjp) throws Throwable {
        OrderMqVo orderMqVo= (OrderMqVo) pjp.getArgs()[0];
        String uuid= orderMqVo.getUuid();
        if (StringUtils.isEmpty(uuid)) {
            return null;
        }
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(uuid, 1,2, TimeUnit.MINUTES);
        if(!lock){
            return null;
        }
        try {
            return pjp.proceed();
        }catch (Exception e){
            redisTemplate.delete(uuid);
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
    }
}
